import { getPostsPage, getAllCategories, type PostQueryParams, type PostPageResult } from '@/lib/index'
import { Suspense } from 'react'
import FilteredPosts from '@/components/FilteredPosts'

interface SearchParams {
    page?: string
    categoryId?: string
    pageSize?: string
}
interface Props {
    searchParams: SearchParams
}

function parseNumberParam(param: string | undefined, defaultValue: number): number {
    if (!param) return defaultValue
    const parsed = Number(param)
    return isNaN(parsed) || parsed < 1 ? defaultValue : parsed
}

export default async function Posts({ searchParams }: Props) {
  const page = parseNumberParam(searchParams.page, 1)
  const pageSize = parseNumberParam(searchParams.pageSize, 10)
  const categoryId = searchParams.categoryId ? parseInt(searchParams.categoryId, 10) : undefined
  
  const queryParams: PostQueryParams = {
    page,
    pageSize,
    categoryId,
  }

  const postPage:PostPageResult = await getPostsPage(queryParams)
  const categories = await getAllCategories()
  return (
    <main className="min-h-screen p-4 md:p-8">
      <div className="max-w-4xl mx-auto">
        <Suspense fallback={<div>加载中...</div>}>
          <FilteredPosts postPage={postPage} categories={categories}/>
        </Suspense>
      </div>
    </main>
  )
} 